package cn.itcast.wushangxiantu.Fragment.guozhan;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;

import cn.itcast.wushangxiantu.UserData.User;
import cn.itcast.wushangxiantu.UserData.UserJuanXianNumber;
import cn.itcast.wushangxiantu.Activity.Login;
import cn.itcast.wushangxiantu.MessageEvent;
import cn.itcast.wushangxiantu.OkhttpUtil;
import cn.itcast.wushangxiantu.R;
import cn.itcast.wushangxiantu.ToastUtil;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link MeiRiJuanXianFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class MeiRiJuanXianFragment extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private Context context;
    private int gj_di;
    private View view;
    private ViewHolder viewHolder;

    public MeiRiJuanXianFragment(Context context, int gj_di) {
        this.context = context;
        this.gj_di = gj_di;
    }

    public MeiRiJuanXianFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment MeiRiJuanXianFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static MeiRiJuanXianFragment newInstance(String param1, String param2) {
        MeiRiJuanXianFragment fragment = new MeiRiJuanXianFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view = inflater.inflate(R.layout.fragment_mei_ri_juan_xian, container, false);
        viewHolder=new ViewHolder(view);
        return view;
    }

    class ViewHolder implements View.OnClickListener {
        public View rootView;
        public Button btnGw;
        public TextView tvGWNumber;
        public Button btnMoney;
        public TextView tvMoenyNumber;
        public Button btnSH;
        public TextView tvSHNumber;

        public ViewHolder(View rootView) {
            this.rootView = rootView;
            this.btnGw = (Button) rootView.findViewById(R.id.btnGw);
            this.tvGWNumber = (TextView) rootView.findViewById(R.id.tvGWNumber);
            this.btnMoney = (Button) rootView.findViewById(R.id.btnMoney);
            this.tvMoenyNumber = (TextView) rootView.findViewById(R.id.tvMoenyNumber);
            this.btnSH = (Button) rootView.findViewById(R.id.btnSH);
            this.tvSHNumber = (TextView) rootView.findViewById(R.id.tvSHNumber);
            getUserJuanXian(Login.getUser().getUsernumber(),Login.getUser().getPassword());
            btnGw.setOnClickListener(this);
            btnMoney.setOnClickListener(this);
            btnSH.setOnClickListener(this);
        }

        @Override
        public void onClick(View view) {
            switch (view.getId()){
                case R.id.btnGw:
                    GeneralDialog("输入捐献数目",0);
                    break;
                case R.id.btnMoney:
                    GeneralDialog("输入捐献数目",1);
                    break;
                case R.id.btnSH:
                    GeneralDialog("输入捐献数目",2);
                    break;
            }
        }
    }

    private void getUserJuanXian(String usernumber, String password) {
        OkhttpUtil.getRequest(OkhttpUtil.URL_LOG + "&need=getUserJuanXian" + "&userNumber=" + usernumber + "&passWord=" + password, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                try {
                    Log.v("getUserJuanXian",e.getMessage());
                }catch (Exception e1){

                }
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res=response.body().string();
                Log.v("getUserJuanXian",res);
                UserJuanXianNumber user=new Gson().fromJson(res,UserJuanXianNumber.class);
                Message message=new Message();
                message.what=1;
                message.obj=user;
                handler.sendMessage(message);
            }
        });
    }
    Handler handler=new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message message) {
            switch (message.what){
                case 1:
                    UserJuanXianNumber userJuanXianNumber= (UserJuanXianNumber) message.obj;
                    if (null!=userJuanXianNumber){
                        viewHolder.tvGWNumber.setText("今日剩余数量:"+userJuanXianNumber.getGxgwnumber());
                        viewHolder.tvMoenyNumber.setText("今日剩余数量:"+userJuanXianNumber.getGxjbnumber());
                        viewHolder.tvSHNumber.setText("今日剩余数量:"+userJuanXianNumber.getGxshnumber());
                    }else {
                        ToastUtil.toast(context);
                    }
                    break;
                case 2:
                    User user= (User) message.obj;
                    if (null!=user){
                        GeneralDialog("捐献详情",user.getStw());
                        EventBus.getDefault().post(new MessageEvent("getGuoJiaXinxi"));
                        getUserJuanXian(Login.getUser().getUsernumber(),Login.getUser().getPassword());
                    }else {
                        ToastUtil.toast(context);
                    }
                    break;
            }
            return false;
        }
    });
    private void GeneralDialog(String hand, final int id) {
        /**
         * 编辑框
         * 1标题
         */
        final AlertDialog dialog;
        final EditText editText = new EditText(context);
        editText.setLines(1);
        editText.setInputType(InputType.TYPE_CLASS_NUMBER);
        String content = hand;
        final AlertDialog.Builder builder = new AlertDialog.Builder(context)
                .setTitle(content)
                .setView(editText)
                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                       int number=Integer.parseInt(editText.getText().toString().trim());
                       if (number<=0){
                           ToastUtil.toast(context,"输入正确的数字");
                       }else {
                            JuanXian(Login.getUser().getUsernumber(),Login.getUser().getPassword(),id,number);
                       }
                    }
                });
        dialog = builder.create();
        dialog.show();
    }

    public void GeneralDialog(String head, String content) {
        /**
         * 普通对话框
         * 1标题
         * 2内容
         */
        AlertDialog dialog;
        AlertDialog.Builder builder = new AlertDialog.Builder(context)
                .setTitle(head)

                .setMessage(content)
                .setNegativeButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                    }
                });
        dialog = builder.create();
        dialog.show();
    }

    private void JuanXian(String usernumber, String password, int num, int number) {
        OkhttpUtil.getRequest(OkhttpUtil.URL_LOG + "&need=JuanXian" + "&userNumber=" + usernumber + "&passWord=" + password+"&num="+num+"&number="+number, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                try {
                    Log.v("JuanXian",e.getMessage());
                }catch (Exception e1){

                }
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res=response.body().string();
                Log.v("JuanXian",res);
                User user=new Gson().fromJson(res,User.class);
                Message message=new Message();
                message.what=2;
                message.obj=user;
                handler.sendMessage(message);
            }
        });
    }
}